/**
 * The ArrayAdapter for FeedItems
 * @author cathbar
 */
package com.dylankenny.flikrreader.view;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.dylankenny.flikrreader.model.data.FeedItem;
import com.dylankenny.flikrreader.model.parse.NetworkManager;

public class FeedItemAdapter extends ArrayAdapter<FeedItem> {
	private ArrayList<FeedItem> entries;
	private Activity activity;

	public FeedItemAdapter(Activity a, int textViewResourceId, ArrayList<FeedItem> entries) {
		super(a, textViewResourceId, entries);
		this.entries = entries;
		this.activity = a;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;

		final FeedItem custom = this.entries.get(position);
		if (custom != null) {

			ImageView imageView = new ImageView(this.activity.getApplicationContext());
			if (custom.getFilePath() != null && !custom.getFilePath().equals("")) {
				File file = new File(custom.getFilePath());
				if (file.exists()) {
					Bitmap bitmap = decodeSampledBitmapFromFile(custom.getFilePath(), 75, 75);
					imageView.setImageBitmap(bitmap);

					imageView.setLayoutParams(new AbsListView.LayoutParams(75, 75));
					imageView.setScaleType(ScaleType.FIT_XY);

				}
			} else {
				String filename = custom.getMedia().getM();
				if (filename == null || filename.equals("")) {
					filename = custom.getTitle();
				}
				String localFilename = filename.substring(filename.lastIndexOf("/") + 1);
				localFilename = NetworkManager.PATH + localFilename;
				custom.setFilePath(localFilename);
				new LongOperation().execute(filename, custom.getFilePath());

			}

			v = imageView;
		}
		return v;
	}

	private class LongOperation extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			NetworkManager.DownloadImageToFS(params[0], params[1]);
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
			FeedItemAdapter.this.notifyDataSetChanged();
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height / (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}

	public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filename.replace(" .jpg", ".jpg"), options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filename.replace(" .jpg", ".jpg"), options);
	}
}
